<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\common\constant\Constant;
use app\common\model\Proxy;
use app\common\model\ProxyUser;
use app\common\model\User;
use think\Db;
use think\Exception;

class ProxyManager extends BaseManager
{

    /**
     * 用户申请代理
     * @param User $user
     * @param array $data
     * @param bool $trans
     * @return array
     */
    public static function proxy(User $user,array $data,bool $trans=true)
    {
        if ($trans)
            Db::startTrans();
        try {
            if($user->is_authentication == User::IS_AUTHENTICATION_NO){
                throw new Exception('您当前未实名认证，无法申请代理');
            }
            if ( Proxy::where('user_id',$user->id)->where('status','<>',Proxy::STATUS_REJECT)->find()){
                throw new Exception('您当前已申请代理或成为代理，请勿重复申请');
            }
            $data['rate'] = 10;
            $data['user_id'] = $user->id;
            $data['create_time'] = time();
            $data['update_time'] = time();

            if(!Proxy::create($data)){
                throw new Exception('申请失败');
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取当前用户最近申请记录
     * @param User $user
     * @return array
     */
    public static function getProxyDetail(User $user){
        try {
            $proxyInfo = Proxy::where('user_id',$user->id)->order('id desc')->find();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($proxyInfo);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 代理统计数据
     * @param $money
     * @param $date
     * @param $user_id
     * @param $proxy_id
     * @param $trans
     * @return array
     */
    public static function Statistics($money,$date,$user_id,$proxy_id,$trans=true){
        if($trans)
            Db::startTrans();
        try {
            $money = bcadd($money,0,2);

            $time = strtotime($date);
            $year = intval(date('Y',$time));
            $month = intval(date('m',$time));
            $day = intval(date('d',$time));
            if(Proxy\Statistics::where('type',Proxy\Statistics::TYPE_YEAR)->where('user_id',$user_id)->where('proxy_id',$proxy_id)->where('year',$year)->find()){
                Proxy\Statistics::where('type',Proxy\Statistics::TYPE_YEAR)->where('user_id',$user_id)->where('proxy_id',$proxy_id)->where('year',$year)->update([
                    'money'=>Db::raw('money + '.$money),
                    'update_time'=>time(),
                ]);
            }else{
                Proxy\Statistics::create([
                    'type'=>Proxy\Statistics::TYPE_YEAR,
                    'proxy_id'=>$proxy_id,
                    'user_id'=>$user_id,
                    'money'=> $money,
                    'year'=> $year,
                    'create_time'=> time(),
                    'update_time'=> time(),
                ]);
            }

            if(Proxy\Statistics::where('type',Proxy\Statistics::TYPE_MONTH)->where('user_id',$user_id)->where('proxy_id',$proxy_id)->where('year',$year)->where('month',$month)->find()){
                Proxy\Statistics::where('type',Proxy\Statistics::TYPE_MONTH)->where('user_id',$user_id)->where('proxy_id',$proxy_id)->where('year',$year)->where('month',$month)->update([
                    'money'=>Db::raw('money + '.$money),
                    'update_time'=>time(),
                ]);
            }else{
                Proxy\Statistics::create([
                    'type'=>Proxy\Statistics::TYPE_MONTH,
                    'proxy_id'=>$proxy_id,
                    'user_id'=>$user_id,
                    'money'=> $money,
                    'year'=> $year,
                    'month'=> $month,
                    'create_time'=> time(),
                    'update_time'=> time(),
                ]);
            }


            if(Proxy\Statistics::where('type',Proxy\Statistics::TYPE_DAY)->where('user_id',$user_id)->where('proxy_id',$proxy_id)->where('year',$year)->where('month',$month)->where('day',$day)->find()){
                Proxy\Statistics::where('type',Proxy\Statistics::TYPE_DAY)->where('user_id',$user_id)->where('proxy_id',$proxy_id)->where('year',$year)->where('month',$month)->where('day',$day)->update([
                    'money'=>Db::raw('money + '.$money),
                    'update_time'=>time(),
                ]);
            }else{
                Proxy\Statistics::create([
                    'type'=>Proxy\Statistics::TYPE_DAY,
                    'proxy_id'=>$proxy_id,
                    'user_id'=>$user_id,
                    'money'=> $money,
                    'year'=> $year,
                    'month'=> $month,
                    'day'=> $day,
                    'create_time'=> time(),
                    'update_time'=> time(),
                ]);
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    public static function ProxyUser($userId,$page=1,$step=Constant::PAGE_LIMIT):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page < 1){
            $page = 1;
        }
        try {
            $start = ($page-1)*$step;
            $proxyInfo = Proxy::where('user_id',$userId)->where('status',Proxy::STATUS_ENDORSE)->find();
            if (!$proxyInfo){
                throw new Exception('您不是代理用户，请正确操作');
            }

            $proxyUserModel = new ProxyUser();
            $count = $proxyUserModel->where('p_user_id',$userId)->count();
            $info = $proxyUserModel->alias('pu')
                ->join('user u','u.id = pu.user_id','inner')
                ->where('pu.p_user_id',$userId)
                ->field('pu.id,pu.create_time,u.avatar,u.mobile,u.nickname')
                ->limit($start,$step)
                ->order('pu.id desc')
                ->select();
            if ($info){
                foreach ($info as $k=>&$v){
                    if ($v->avatar && strrpos($v->avatar,'https')===false){
                        $v->avatar = cdnurl($v->avatar);
                    }

                    if ($v->mobile){
                        $v->mobile = desensitize($v->mobile,3,5);
                    }
                }
            }
            $pageData = page($count,$step,$page);
            $return['list'] = $info;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }
}